import roleData from './role'
import userData from './user'
import routerData from './router'
import jwt from 'jsonwebtoken'
import requestRole from './requestRole'
import fs from "fs";
import path from 'path'
export default [
    // 登录
    {
        url: '/login',
        method: 'POST',
        response(req) {
            let { username, password } = req.body
            let user = userData.find(item => item.username === username && item.password === password)
            console.log(username, password, user)
            if (user) {
                let role = roleData.find(item => item.id === user.roleId)
                let token = jwt.sign({
                    username,
                    password,
                    id: user.id
                }, 'asdasdfdgfa')
                if (role.routerId === "*") {
                    return {
                        code: 200,
                        msg: '登录成功',
                        username: user.username,
                        role: role.role,
                        token,
                        routerData
                    }
                } else {
                    return {
                        code: 200,
                        msg: '登录成功',
                        username: user.username,
                        role: role.role,
                        token,
                        routerData: routerData.filter(item => role.routerId.includes(item.id))
                    }
                }

            } else {
                req.body = {
                    code: 400,
                    msg: '登录失败'
                }
            }

        }
    },

    // 获取用户列表
    {
        url: '/user/getlist',
        method: 'get',
        response() {
            return {
                code: 200,
                msg: '获取成功',
                userData
            }
        }
    },
    {
        url: '/role/getlist',
        method: 'get',
        response() {
            return {
                code: 200,
                msg: '获取成功',
                routerData
            }
        }
    },
    {
        url: '/api/role/add',
        method: "post",
        response(ctx) {
            console.log(ctx)
            let { role, routerId } = ctx.body
            let fsData = fs.readFileSync(path.join(__dirname, './role.js'), 'utf-8')
            let fslist = JSON.parse(fsData)
            fslist.push({
                id: +new Date,
                role: role,
                routerId: routerId
            })
            fs.writeFileSync(path.join(__dirname, './role.js'), JSON.stringify(fslist))
            return {
                code: 200,
                msg: '添加成功'
            }
        }
    },
    // 获取权限信息
    ...requestRole
]